﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Drawing;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using Vmago.Models;
using Batch.Entity;
using Batch.Common;
using Vmago.Models.DBML;
using System.Text.RegularExpressions;


namespace Vmago.Controllers
{
    [HandleError]
    [OutputCache(Location = OutputCacheLocation.None)]
    public class AccountController : ControllerBase
    {
        #region Global：变量

        private IUserProfile _userProfile;
        private ISysCategory _sysCategory;
        private ICategory _cityMasterCategory;

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public MembershipProvider Provider
        {
            get;
            private set;
        }

        //  function for testing MVC with Jquery on front-end   
        public struct checkLoginResult
        {
            public string result;
        }


        #endregion

        #region Global：构造函数

        public AccountController()
            : this(null, null)
        {
            _userProfile = new RepositoyUserProfile();
            _sysCategory = new RepositorySysCategory();
            _cityMasterCategory = new RepositoryCategory();

        }

        // This constructor is not used by the MVC framework but is instead provided for ease
        // of unit testing this type. See the comments at the end of this file for more
        // information.

        public AccountController(IFormsAuthentication formsAuth, MembershipProvider provider)
        {
            FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
            Provider = provider ?? Membership.Provider;
        }

        #endregion

        #region ChangePassword：页面初始化

        [Authorize]
        public ActionResult ChangePassword()
        {

            ViewData["Title"] = "Change Password";
            ViewData["PasswordLength"] = Provider.MinRequiredPasswordLength;

            return View();
        }

        #endregion

        #region ChangePassword：修改密码

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {

            ViewData["Title"] = "密码更改";
            ViewData["PasswordLength"] = Provider.MinRequiredPasswordLength;

            // Basic parameter validation
            if (String.IsNullOrEmpty(currentPassword))
            {
                ModelState.AddModelError("currentPassword", "原始密码不可为空。");
            }
            if (newPassword == null || newPassword.Length < Provider.MinRequiredPasswordLength)
            {
                ModelState.AddModelError("newPassword",
                    String.Format(CultureInfo.CurrentCulture,
                         "输入一个 {0} 位或更长的字符。",
                         Provider.MinRequiredPasswordLength));
            }
            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("_FORM", "新密码不可为空。");
            }

            if (ModelState.IsValid)
            {
                // Attempt to change password
                MembershipUser currentUser = Provider.GetUser(User.Identity.Name, true /* userIsOnline */);
                bool changeSuccessful = false;
                try
                {
                    changeSuccessful = currentUser.ChangePassword(currentPassword, newPassword);
                }
                catch
                {
                    // An exception is thrown if the new password does not meet the provider's requirements
                }

                if (changeSuccessful)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("_FORM", "原始密码是错误的。");
                }
            }

            // If we got this far, something failed, redisplay form
            return View();
        }

        #endregion

        #region ChangePasswordSuccess：页面初始化

        public ActionResult ChangePasswordSuccess()
        {

            ViewData["Title"] = "更改密码";

            return View();
        }

        #endregion

        #region CityContent：页面初始化

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CityContent()
        {
            return View();
        }

        #endregion

        #region LoginViewData：页面初始化

        // This function is used to refresh the view data in the login page 
        // Author: wenyan
        // Date: 2008.11.1
        private void LoginViewData()
        {
            ViewData["Title"] = "登录";
            ViewData["lbHead"] = "登录Vmago爬爬网帐户";
            ViewData["lbUsername"] = "用户名";
            ViewData["lbPassword"] = "密码";
            ViewData["lbRemindMe"] = "记住我";
            ViewData["lbLogin"] = "登录";
            ViewData["Date"] = System.DateTime.Now.ToLongDateString();
        }

        #endregion

        #region Login：页面初始化

        public ActionResult Login()
        {

            LoginViewData();

            return View();
        }

        #endregion

        #region Login：登录

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string username, string password, bool rememberMe, string returnUrl, string Login)
        {
            if (Login.Equals("注册"))
            {
                RegisterViewData();
                return View("Register");
            }

            LoginViewData();

            // 验证 用户名、密码是否为空
            if (String.IsNullOrEmpty(username) || username.Equals("Email或昵称"))
            {
                ModelState.AddModelError("username1", LoginGetErrMsg("username"));
                username = null;
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password1", LoginGetErrMsg("password"));
            }

            if (ViewData.ModelState.IsValid)
            {
                // Attempt to login
                bool loginSuccessful = Provider.ValidateUser(username, password);

                if (loginSuccessful)
                {

                    FormsAuth.SetAuthCookie(username, rememberMe);

                    MembershipUser NowUser = Membership.GetUser(username);

                    if (NowUser != null && NowUser.IsOnline)
                    {
                        Session["IsOnline"] = true;
                        UtilController u = new UtilController();
                        if (u.isShop(NowUser.ProviderUserKey))
                        {
                            Session["IsShop"] = true;
                        }
                        else
                        {
                            Session["IsShop"] = false;
                        }
                    }

                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("Validation", LoginGetErrMsg("validation"));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["rememberMe"] = rememberMe;

            return View();
        }

        #endregion

        #region Logout：页面初始化

        public ActionResult Logout()
        {
            FormsAuth.SignOut();
            return RedirectToAction("Index", "Home");
        }

        #endregion

        #region VerifyLogin：页面初始化

        public ActionResult VerifyLogin()
        {
            return View();
        }

        #endregion

        //#region OpenLogin：页面初始化

        //public ActionResult OpenLogin()
        //{
        //    LoginViewData();

        //    return View();
        //}

        //#endregion

        #region VerifyLoginJason：...

        public ActionResult VerifyLoginJason(string username)
        {
            if (username == "abc")
            {
                return this.Json(new
                {
                    result = 1
                });
            }
            else
            {
                return this.Json(new
                {
                    result = 0
                });
            }
        }

        #endregion

        #region MailContact：页面初始化

        public ActionResult MailContact()
        {

            MailContactViewData();

            return View();
        }

        #endregion

        #region MailContact：...

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult MailContact(string username, string password)
        {
            MailContactViewData();

            if (String.IsNullOrEmpty(username.Trim()))
            {
                ViewData.ModelState.AddModelError("VMusername", "邮箱地址不可为空。");
            }
            if (!Regex.IsMatch(username.Trim(), @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
            {
                ViewData.ModelState.AddModelError("VMusername", "邮箱地址不合法。");
            }
            if (String.IsNullOrEmpty(password.Trim()))
            {
                ViewData.ModelState.AddModelError("VMpassword", "密码不可为空。");
            }

            if (!ModelState.IsValid)
            {
                ViewData["username"] = username;
                ViewData["password"] = password;
                return View("MailContact");
            }

            List<String> FriendMail = new List<String>();
            String MailName = String.Empty;
            String MailPass = String.Empty;
            String MailType = String.Empty;

            if (String.IsNullOrEmpty(password))
            {
                ViewData["Message"] = "请输入可用邮箱账户及密码";
                return View();
            }
            else if (username.ToLower().EndsWith("gmail.com"))
            { MailType = "gmail"; }
            else if (username.ToLower().EndsWith("yahoo.com") || username.ToLower().EndsWith("yahoo.cn"))
            { MailType = "yahoo"; }
            else if (username.ToLower().EndsWith("live.com") || username.ToLower().EndsWith("hotmail.com") || username.ToLower().EndsWith("live.cn"))
            { MailType = "msn"; }
            else
            {
                ViewData["Message"] = "请输入可用邮箱账户及密码";
                return View();
            }


            switch (MailType)
            {
                case "gmail":
                    Batch.Helper.GmailHelper gmail = new Batch.Helper.GmailHelper();
                    FriendMail = gmail.getLinkmans(username, password); break;
                case "yahoo":
                    Batch.Helper.YahooHelper yahoo = new Batch.Helper.YahooHelper();
                    FriendMail = yahoo.getLinkmans(username, password); break;
                case "msn":
                    Batch.Helper.MsnHelper msn = new Batch.Helper.MsnHelper();
                    msn.Start(username, password);
                    FriendMail = msn.getFriendMail(); break;
                default: break;
            }
            //List<Batch.Entity.MsnFriend> FriendName = MSN.getFriends();
            MailName = username;
            MailPass = password;
            return View(FriendMail);
        }

        #endregion

        #region UserProfile：页面初始化

        public ActionResult UserProfile()
        {

            if (Request.IsAuthenticated)
            {
                UserProfile_Init();
                return View();
            }
            else
            {
                return RedirectToAction("Login");
            }

        }

        private void UserProfile_Init()
        {
            //try
            //{
            UserProfileViewData();
            IEnumerable<UserProfile> UserProfile = _userProfile.GetSingleUserProfile();

            foreach (UserProfile u in UserProfile)
            {

                if (u.Name != null) { ViewData["Name"] = u.Name.ToString(); }
                if (u.MSN != null) { ViewData["Msn"] = u.MSN.ToString(); }
                if (u.QQ != null) { ViewData["QQ"] = u.QQ.ToString(); }
                if (u.Hometown != null) { ViewData["Hometown"] = u.Hometown.ToString(); }
                if (u.PostCode != null) { ViewData["Postcode"] = u.PostCode.ToString(); }
                if (u.Landline != null) { ViewData["Landline"] = u.Landline.ToString(); }
                if (u.Mobile != null) { ViewData["Mobile"] = u.Mobile.ToString(); }

                if (u.Gender != null)
                { ViewData["Gender"] = new SelectList(_sysCategory.GetSysCategory("Gender"), "CategoryValueID", "CategoryValue", u.Gender); }
                else { ViewData["Gender"] = new SelectList(_sysCategory.GetSysCategory("Gender"), "CategoryValueID", "CategoryValue"); }

                ViewData["Year"] = new SelectList(_sysCategory.GetSysCategory("Year"), "CategoryValueID", "CategoryValue");
                ViewData["Month"] = new SelectList(_sysCategory.GetSysCategory("Month"), "CategoryValueID", "CategoryValue");
                ViewData["Day"] = new SelectList(_sysCategory.GetSysCategory("Day"), "CategoryValueID", "CategoryValue");

                if (u.Occupation != null)
                {
                    ViewData["Occupation"] = new SelectList(_sysCategory.GetSysCategory("Occupation"), "CategoryValueID", "CategoryValue", u.Occupation);
                }
                else
                {
                    ViewData["Occupation"] = new SelectList(_sysCategory.GetSysCategory("Occupation"), "CategoryValueID", "CategoryValue");
                }

                if (u.Marital != null)
                { ViewData["Marital"] = new SelectList(_sysCategory.GetSysCategory("Marital"), "CategoryValueID", "CategoryValue", u.Marital); }
                else { ViewData["Marital"] = new SelectList(_sysCategory.GetSysCategory("Marital"), "CategoryValueID", "CategoryValue"); }

                if (u.Body != null)
                {
                    ViewData["Body"] = new SelectList(_sysCategory.GetSysCategory("Body"), "CategoryValueID", "CategoryValue", u.Body);
                }
                else { ViewData["Body"] = new SelectList(_sysCategory.GetSysCategory("Body"), "CategoryValueID", "CategoryValue"); }
                if (u.Blood != null)
                {
                    ViewData["Blood"] = new SelectList(_sysCategory.GetSysCategory("Blood"), "CategoryValueID", "CategoryValue", u.Blood);
                }
                else ViewData["Blood"] = new SelectList(_sysCategory.GetSysCategory("Blood"), "CategoryValueID", "CategoryValue");

            }

            if (checkUpdate())
            {
                ViewData["bl"] = "true";
            }
            else
            {
                ViewData["bl"] = "false";
            }


            //}
            //catch (Exception e)
            //{
            //    return RedirectToAction("Login");
            //}
            //  return View(_userProfile.GetUserProfile());
        }

        #endregion

        #region MailContact_MailSend

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult MailContact_MailSend(String FriendsMail)
        {
            if (String.IsNullOrEmpty(FriendsMail))
            {
                return RedirectToAction("MailContact");
            }
            if (SendMail(FriendsMail, "邀请", "<h1>邀请<h1>"))
            {
                TempData["Message"] = "邀请邮件已发送！";
                return RedirectToAction("MailContact_Message");
            }
            else
            {
                TempData["Message"] = "邀请邮件发送失败请重试！";
                return RedirectToAction("MailContact_Message");
            }
        }

        #endregion

        #region MailContact_Message：页面初始化
        public ActionResult MailContact_Message()
        {
            ViewData["Message"] = (TempData["Message"] != null) ? TempData["Message"].ToString() : String.Empty;
            return View();
        }
        #endregion

        #region UserProfile：...

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UserProfile(string Email, string Name, int Gender, int Year, int Month, int Day, int Occupation, int Marital, int Body, int Blood, string Hometown
                                        , string Postcode, string CurrentAddreass, string Landline, string Mobile, string QQ, string Msn)
        {


            if (String.IsNullOrEmpty(Name))
            {
                ViewData.ModelState.AddModelError("VMName", "姓名不可为空");
            }

            if (String.IsNullOrEmpty(Email))
            {
                ViewData.ModelState.AddModelError("VMEmail", "邮件地址不可为空");
            }

            if (!ViewData.ModelState.IsValid)
            {
                UserProfile_Init();
                ViewData["Name"] = Name;
                ViewData["Email"] = Email;
                return View("UserProfile");
            }


            string username = Membership.GetUser().ProviderUserKey.ToString();
            _userProfile.UpdateUserProfile(username, Email, Name, Gender, Year, Month, Day, Occupation, Marital, Body, Blood, Hometown
                                          , Postcode, CurrentAddreass, Landline, Mobile, QQ, Msn);
            UserProfile_Init();
            return RedirectToAction("UserProfile");
        }

        #endregion

        #region 私有方法：判断用户等级

        private Boolean checkUpdate()
        {
            try
            {
                string[] r = Roles.GetRolesForUser();

                if (r.Last().Equals("consumerVIP") || r.Last().Equals("coporateVIP"))
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return true;
            }
            return true;
        }


        #endregion

        #region ValidationCode：页面初始化

        public ActionResult ValidationCode()
        {
            return View();
        }

        #endregion

        #region ValidationCodeGenerator：页面初始化

        public ActionResult ValidationCodeGenerator()
        {
            string checkCode = GetRandomCode(4);
            Session["CheckCode"] = checkCode;
            SetPageNoCache();
            CreateImage(checkCode);

            return View();

        }

        #endregion

        #region Register：页面初始化

        public ActionResult Register()
        {
            //RegisterViewData();

            return RedirectToAction("UserProfile");
        }

        // This function is used to refresh the view data in the register page 
        // Author: wenyan
        // Date: 2008.11.1
        private void RegisterViewData()
        {
            ViewData["Title"] = "注册";
            ViewData["lbHead"] = "注册您的go2jp.com匯璟网帐户";
            ViewData["lbHeadReminder"] = "请填写以下注册表格：";
            ViewData["lbPasswordLength"] = "密码不得少于" + Provider.MinRequiredPasswordLength + "个字符";
            ViewData["lbUsername"] = "用户名";
            ViewData["lbEmail"] = "电子邮件";
            ViewData["lbPassword"] = "密码";
            ViewData["lbConfirmPassword"] = "确认密码";
            ViewData["lbValidationCode"] = "验证码";
            ViewData["Register"] = "注册";
            ViewData["lbName"] = "姓名";
            ViewData["lbCity"] = "居住的城市";
            ViewData["lbGender"] = "性别";
            ViewData["lbDate"] = "出生年月";
            ViewData["lbOccupation"] = "目前职业";
            ViewData["lbType"] = "注册类型:";
            ViewData["lbTypeNormal"] = "普通用户";
            ViewData["lbTypeBusiness"] = "商户用户";
            ViewData["btChange"] = "看不清，再换一张";

            ViewData["RegGender"] = new SelectList(_sysCategory.GetSysCategory("Gender"), "CategoryValueID", "CategoryValue");
            ViewData["RegYear"] = new SelectList(_sysCategory.GetSysCategory("Year"), "CategoryValueID", "CategoryValue");
            ViewData["RegMonth"] = new SelectList(_sysCategory.GetSysCategory("Month"), "CategoryValueID", "CategoryValue");
            ViewData["RegDay"] = new SelectList(_sysCategory.GetSysCategory("Day"), "CategoryValueID", "CategoryValue");
            ViewData["RegOccupation"] = new SelectList(_sysCategory.GetSysCategory("Occupation"), "CategoryValueID", "CategoryValue");
        }

        #endregion

        #region Register：注册

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(string RegUsername,
            string RegEmail,
            string RegPassword,
            string RegConfirmPassword,
            string RegValidationCode,
            string RegName,
            int RegGender,
            int RegYear,
            int RegMonth,
            int RegDay,
            string RegCity,
            int RegOccupation,
            Boolean RegAgree,
            string Register)
        {


            //refresh the view data in the register page
            RegisterViewData();

            string VU = Request["validationUsername"];

            string VM = Request["validationMail"];

            string VP = Request["validationPassword"];

            string VC = Request["validationConfigPassword"];


            if (Register.Equals("看不清，再换一张") || VU.Equals("有错误!") || VM.Equals("有错误!") || VP.Equals("有错误!") || VC.Equals("有错误!"))
            {

                ViewData["RegGender"] = new SelectList(_sysCategory.GetSysCategory("Gender"), "CategoryValueID", "CategoryValue", RegGender);
                ViewData["RegYear"] = new SelectList(_sysCategory.GetSysCategory("Year"), "CategoryValueID", "CategoryValue", RegYear);
                ViewData["RegMonth"] = new SelectList(_sysCategory.GetSysCategory("Month"), "CategoryValueID", "CategoryValue", RegMonth);
                ViewData["RegDay"] = new SelectList(_sysCategory.GetSysCategory("Day"), "CategoryValueID", "CategoryValue", RegDay);
                ViewData["RegOccupation"] = new SelectList(_sysCategory.GetSysCategory("Occupation"), "CategoryValueID", "CategoryValue", RegOccupation);
                return View("Register");
            }

            string checkCode = Session["CheckCode"].ToString();

            if (String.IsNullOrEmpty(RegUsername) || RegUsername.Equals("请输入昵称"))
            {
                ModelState.AddModelError("RegUsername", RegisterGetErrMsg("RegUsername"));
            }
            if (String.IsNullOrEmpty(RegEmail) || RegEmail.Equals("请输入Email"))
            {
                ModelState.AddModelError("RegEmail", RegisterGetErrMsg("RegEmail"));
            }
            if (RegPassword == null || RegPassword.Length < Provider.MinRequiredPasswordLength)
            {
                ModelState.AddModelError("RegPassword",
                    String.Format(CultureInfo.CurrentCulture,
                         RegisterGetErrMsg("RegPassword"),
                         Provider.MinRequiredPasswordLength));
            }
            if (!String.Equals(RegPassword, RegConfirmPassword, StringComparison.Ordinal))
            {
                ModelState.AddModelError("RegConfirmPassword", RegisterGetErrMsg("RegConfirmPassword"));

            }
            if (String.IsNullOrEmpty(RegValidationCode) || RegValidationCode.Equals("请输入验证码"))
            {
                ModelState.AddModelError("RegValidationCode", RegisterGetErrMsg("RegValidationCodeErr01"));
            }

            if (!RegAgree)
            {
                ModelState.AddModelError("RegAgree", RegisterGetErrMsg("RegAgree"));

            }

            if (RegValidationCode != checkCode)
            {
                ModelState.AddModelError("RegValidationCode", RegisterGetErrMsg("RegValidationCodeErr02"));
            }

            if (ViewData.ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                MembershipUser newUser = Provider.CreateUser(RegUsername, RegPassword, RegEmail, null, null, true, null, out createStatus);
                //If the user dosen't have to write the ValidationCode or have  no choise ,he will not be able to register
                if (newUser != null)
                {
                    FormsAuth.SetAuthCookie(RegUsername, false /* createPersistentCookie */);

                    _userProfile.UpdateUserProfile(newUser.ProviderUserKey.ToString(), RegEmail, RegName, RegGender, RegYear, RegMonth, RegDay, RegOccupation, 0, 0, 0, RegCity
                                               , null, null, null, null, null, null);

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View("Register");
        }

        private string RegisterGetErrMsg(string type)
        {
            string rtn = null;
            switch (type)
            {
                //case "RegUsername":
                //    rtn = "请输入有效用户名";
                //    break;
                //case "RegEmail":
                //    rtn = "请输入有效的电子邮件地址";
                //    break;
                //case "RegPassword":
                //    rtn = "密码长度太短";
                //    break;
                //case "RegConfirmPassword":
                //    rtn = "两次输入密码不一致";
                //    break;
                case "RegValidationCodeErr01":
                    rtn = "请输入验证码";
                    break;
                case "RegValidationCodeErr02":
                    rtn = "验证码错误，请重新输入";
                    break;
                case "RegAgree":
                    rtn = "注册需同意网站条款";
                    break;
                default:
                    Console.WriteLine("Default case");
                    break;
            }
            return rtn;

        }

        #endregion

        #region Register：跳转至商户注册

        public ActionResult TrademarkInformation()
        {
            return View("Register");
        }

        #endregion

        #region GetPassWord：页面初始化

        public ActionResult GetPassWord()
        {
            //ViewData["lbUserName"] = "获取密码";
            //ViewData["tbUserName"] = "登录帐号";
            //ViewData["tbEmail"] = "注册邮件";
            //ViewData["btSendEmail"] = "发送密码邮件";
            return View();
        }

        #endregion

        #region GetEmail：获取并发送密码邮件

        public ActionResult GetEmail(String tbUserName, String tbEmail)
        {

            try
            {
                String strEmail = string.Empty;
                if (String.IsNullOrEmpty(tbUserName.Trim()))
                {
                    ViewData.ModelState.AddModelError("VMUserName", "注册帐号不可为空。");
                }
                if (!Regex.IsMatch(tbEmail.Trim(), @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                {
                    ViewData.ModelState.AddModelError("VMEmails", "注册邮箱不合法。");
                }
                else if (!String.IsNullOrEmpty(tbUserName.Trim()))
                {

                    var f = new MembershipDataContext();
                    var a = from m in f.aspnet_Users
                            where m.UserName == tbUserName
                            select m.aspnet_Membership.Email;
                    strEmail = a.First();

                    if (!String.Equals(strEmail.Trim(), tbEmail.Trim()))
                    {
                        ViewData.ModelState.AddModelError("VMEmails", "注册邮箱错误");
                    }
                }

                if (!ModelState.IsValid)
                {
                    ViewData["UserName"] = tbUserName;
                    ViewData["Email"] = tbEmail;
                    return View("GetPassWord");
                }



                String strNewPass = String.Empty;
                MembershipUser currentUser = Provider.GetUser(tbUserName, true /* userIsOnline */);
                strNewPass = currentUser.ResetPassword();
                SendMail(strEmail + "| ", "密码找回", "您的新密码是：<br/>" + strNewPass);

                this.TempData["Message"] = "密码修改成功，请登录注册邮箱获取！";
                return RedirectToAction("GetPassWord_Message", "Account");
            }
            catch
            {
                // An exception is thrown if the new password does not meet the provider's requirements
                return RedirectToAction("GetPassWord", "Account");
            }
        }

        #endregion

        #region GetPassWord_Message：页面初始化

        public ActionResult GetPassWord_Message()
        {
            ViewData["Message"] = (TempData["Message"] != null) ? TempData["Message"].ToString() : String.Empty;
            return View();
        }
        #endregion

        #region UserInfo：页面初始化

        public ActionResult UserInfo()
        {
            UserProfile_Init();
            return View();
        }
        #endregion

        #region 公有方法：用户名唯一性验证

        public void ValidationRegisterUsername(string id)
        {
            List<object> obj = new List<object>();
            IEnumerable<User> c = _userProfile.ValidateUserName(id);
            User cc = null;
            string s = "";
            for (int i = 0; i < c.Count(); i++)
            {
                cc = c.ElementAt(i);
                s = cc.UserName.ToString();
            }
            if (s == "")
            {
                s = "1";
            }
            obj.Add(s);

            RenderJSON(obj);
        }

        #endregion

        #region 公有方法：用户邮箱唯一性验证

        public void ValidationRegisterMail(string id)
        {
            List<object> obj = new List<object>();
            IEnumerable<UserMembership> c = _userProfile.ValidateUserMail(id);
            UserMembership cc = null;
            string s = "";
            for (int i = 0; i < c.Count(); i++)
            {
                cc = c.ElementAt(i);
                s = cc.User.ToString();
            }
            if (s == "")
            {
                s = "1";
            }
            obj.Add(s);

            RenderJSON(obj);

        }

        #endregion

        #region 公有方法：测试jqueryAjax

        public void Ajax(int id)
        {
            switch (id)
            {
                case 1:
                    Console.WriteLine("1");
                    break;
                case 2:
                    Console.WriteLine("2");
                    break;
                case 3:
                    Console.WriteLine("3");
                    break;
            }
        }

        #endregion

        #region 公有方法：JsonResult

        public JsonResult CheckLogin()
        {
            checkLoginResult r = new checkLoginResult();
            r.result = "It's a valid Login";
            return Json(r);
        }

        #endregion

        #region 私有方法：MailContactViewData

        private void MailContactViewData()
        {
            ViewData["Title"] = "邀请好友";
            ViewData["lbHead"] = "邀请你联系列表中的好友";
            ViewData["lbUsername"] = "邮箱地址";
            ViewData["lbPassword"] = "密码";
            ViewData["lnImportContact"] = "登录";
            ViewData["lnMailSend"] = "发送邀请邮件";
            ViewData["Date"] = System.DateTime.Now.ToLongDateString();
        }

        #endregion

        #region 私有方法：UserProfileViewData

        // This function is used to set the view data in the user profile page
        // Author: wenyan 
        // Date: 2008.11.3
        private void UserProfileViewData()
        {
            //UserProfileDataContext dataContext = new UserProfileDataContext();

            //String username = Membership.GetUser().ProviderUserKey.ToString();
            //var u = (from p in dataContext.UserProfiles
            //         where p.UserId.Equals(username)
            //         select p).Single();
            //var k = (from p in dataContext.UserMemberships
            //         where p.UserId.Equals(username)
            //         select p).Single();

            ViewData["Title"] = "用户信息";
            ViewData["lbHead"] = "用户信息";
            ViewData["lbUserName"] = "用户名";
            ViewData["UserName"] = Membership.GetUser().UserName.ToString();
            ViewData["lbUpdate"] = "更新";
            ViewData["lbEmail"] = "电子邮件";
            ViewData["Email"] = Membership.GetUser().Email.ToString();
            ViewData["lbName"] = "姓名";
            ViewData["lbGender"] = "性别";
            ViewData["lbBirthday"] = "生日";
            ViewData["lbOccupation"] = "目前职业";
            ViewData["lbHometown"] = "家乡";
            ViewData["lbPostCode"] = "邮编";
            ViewData["lbCurrentAddreass"] = "目前住址";
            ViewData["lbMarital"] = "婚姻状况";
            ViewData["lbBody"] = "体型";
            ViewData["lbBlood"] = "血型";
            ViewData["lbLandline"] = "固定电话";
            ViewData["lbMobile"] = "移动电话";
            ViewData["lbQQ"] = "QQ号码";
            ViewData["lbMSN"] = "MSN";

        }

        #endregion

        #region 私有方法：LoginGetErrMsg

        private string LoginGetErrMsg(string type)
        {
            string rtn = null;
            switch (type)
            {

                case "username":
                    rtn = "请输入正确的用户名";
                    break;
                case "password":
                    rtn = "请输入正确的密码";
                    break;
                case "validation":
                    rtn = "输入的用户名或者密码不正确";
                    break;
                default:
                    Console.WriteLine("Default case");
                    break;
            }
            return rtn;

        }

        #endregion

        #region 私有方法：SetPageNoCache

        private void SetPageNoCache()
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
        }

        #endregion

        #region 私有方法：CreateRandomCode

        private string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(10);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);//性能问题
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }

        #endregion

        #region 私有方法：GetRandomCode

        private string GetRandomCode(int CodeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9";
            string[] allCharArray = allChar.Split(',');
            string RandomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < CodeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(10);
                while (temp == t)
                {
                    t = rand.Next(10);
                }
                temp = t;
                RandomCode += allCharArray[t];
            }
            return RandomCode;
        }

        #endregion

        #region 私有方法：CreateImage

        private void CreateImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 14.5)), 24);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                //System.Drawing.Drawing2D.LinearGradientBrush brush=new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0,0,image.Width,image.Height),Color.Blue,Color.Blue,1.0f,true);

                g.DrawString(checkCode, font, brush, 4, 2);

                //画图片的前景噪音点
                //for(int i=0; i<100; i++)
                //{
                //    int x = random.Next(image.Width);
                //    int y = random.Next(image.Height);
                //    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                //    image.SetPixel(x,y,Color.Yellow );
                //}

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        #endregion

        #region 私有方法：ErrorCodeToString

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

        #endregion

        #region 保护方法：OnActionExecuting

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity is WindowsIdentity)
            {
                throw new InvalidOperationException("Windows authentication is not supported.");
            }
        }

        #endregion

        #region 私有方法：邮件发送

        private Boolean SendMail(String To, String Tile, String Body)
        {
            try
            {
                String[] FriendMail = To.Split('|');
                MailInfo m = new MailInfo();
                m.UserName = "aresjzj@gmail.com";              //发件人帐号
                m.Password = "geniusares";              //邮箱密码
                m.Smtp = "smtp.gmail.com";          //smtp服务器
                m.Port = 587;                       //smtp服务器服务端口
                m.Ssl = true;                       //是否ssl加密
                m.Title = Tile;
                m.Body = Body;

                //获取好友emial
                for (int i = 0; i < FriendMail.Length - 1; i++)
                {
                    m.AddTo(FriendMail[i]);
                }
                m.IsBodyHtml = true;                //内容解析html
                SendMail send = new SendMail(m);
                send.Send();
            }
            catch
            {
                return false;
            }
            return true;
        }

        #endregion

        #region Ajax：存在性Check：MemberShip


        public JsonResult Ajax_CheckExist_MemberShip(String id)
        {
            return Json(Membership.GetUser(id) == null);
        }

        #endregion
    }

    public interface IFormsAuthentication
    {
        void SetAuthCookie(string userName, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationWrapper : IFormsAuthentication
    {
        public void SetAuthCookie(string userName, bool createPersistentCookie)
        {
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }
        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }

}
